package com.kucunProject.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class EncodingFilter implements Filter{

	String newEncoding = null;
	String oldEncoding = null;
	public void destroy() {

	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain) throws IOException, ServletException {
		
		Map map = new HashMap();
		Enumeration names = servletRequest.getAttributeNames();
		while(names.hasMoreElements()){
			String name = (String)names.nextElement();
			String value = servletRequest.getParameter(name);
			String newValue = new String(value.getBytes(oldEncoding),newEncoding);
			map.put(name, newValue);
		}
		servletRequest.setAttribute("map", map);
		servletResponse.setContentType("text/html;chainset=utf-8");
		
		filterChain.doFilter(servletRequest, servletResponse);
	}

	public void init(FilterConfig config) throws ServletException {
		this.newEncoding = config.getInitParameter("newEncoding");
		this.oldEncoding = config.getInitParameter("oldEncoding");
	}

}
